package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.*;
import com.burgeon.backend.SHOP.entity.presell.Earnest;
import com.burgeon.backend.SHOP.entity.presell.EarnestVO;
import com.burgeon.backend.SHOP.entity.presell.Presell;
import com.burgeon.backend.SHOP.mappers.AppPresellMapper;
import com.burgeon.backend.SHOP.mappers.GoodsMapper;
import com.burgeon.backend.SHOP.mappers.OrderMapper;
import com.burgeon.backend.SHOP.rest.CreateYC_YSRETAIL;
import com.burgeon.backend.SHOP.service.*;
import com.burgeon.backend.SHOP.service.ex.OrderExceptionApp;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.QueueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.burgeon.backend.SHOP.service.Impl.OrderServiceImpl.getOrderIdByUUId;

@Service
public class AppPresellServiceImpl implements AppPresellService {
    @Autowired
    private AppPresellMapper appPresellMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private AddressService addressService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PayWechatService payWechatService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MailService mailService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private QueueService queueService;

    @Override
    public String getImg(String account) {
        return appPresellMapper.findImg(account)+"?"+((Math.random() * 9 + 1) * 100000);
    }

    @Override
    public void startPayingBalancePayment() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String now = String.valueOf(Integer.parseInt(sdf.format(new Date())));
        List<EarnestVO> data = appPresellMapper.earnestAll(now);
        for (EarnestVO earnestVO : data){
            queueService.payingBalancePayment(earnestVO.getGoodsName(),
                    earnestVO.getRem(),earnestVO.getEndTime(),earnestVO.getOpenid(),
                    earnestVO.getToken());
        }

    }

    @Override
    public PayData payForThebalance(String pid, String aid, String mid, String phone, String uid, String openid, String token) throws OrderExceptionApp {
       //修改订单地址 查询订单id 修改邮费
        Order order = appPresellMapper.findOrderByPid(pid);
        if (null == order){
            throw new OrderExceptionApp("订单不存在");
        }
        Mail mail = mailService.GetMail(mid);
        Address address = addressService.getAddressById(aid);
        appPresellMapper.upOrderAddressById(order.getId(),address.getReceiver(),address.getPhone(),address.getAddress(),mail.getPrice());
        order.setMailFee(mail.getPrice());

        return orderService.payForThebalance(order, address, phone, mail, "",  openid, token);
    }

    @Override
    public EarnestVO OrderConfigData(String id) {
        EarnestVO data = appPresellMapper.OrderConfigData(id);
        data.setGoods(goodsMapper.getGoodsById(data.getGid()));
        return data;
    }

    /**
     * 预售定金列表 已支付定金 尾款支付未开始
     * @param uid
     * @param token
     * @return
     */
    @Override
    public List<EarnestVO> presellOrderData(String uid, String token) {
        List<EarnestVO> data = new ArrayList<EarnestVO>();
        List<EarnestVO> earnestVOs = appPresellMapper.presellOrderData(uid, token);
        SimpleDateFormat sdf  = new SimpleDateFormat("yyyyMMdd");
        int now = Integer.parseInt(sdf.format(new Date()));
        for (EarnestVO earnestVO :earnestVOs){

            if (earnestVO!=null&& earnestVO.getClearingTime()!=null&&now<Integer.parseInt(earnestVO.getClearingTime())){
                earnestVO.setGoods(goodsMapper.getGoodsById(earnestVO.getGid()));
                data.add(earnestVO);
            }
        }
        return data;
    }

    @Override
    public void findEarnestResult(String id) throws OrderExceptionApp {
        String result = appPresellMapper.findEarnestResult(id);
        if (!"Y".equals(result)){
            throw new OrderExceptionApp("支付失败");
        }
    }

    @Override
    public void upEarnestState(String id,String erpId,String state) {
         appPresellMapper.upEarnestState(id,erpId,state);
    }


    @Override
    public Earnest getEarnestDataByCode(String code) {
        return appPresellMapper.getEarnestDataByCode(code);
    }

    @Override
    public String agreementData(String token) {
        return appPresellMapper.getAgreement(token);
    }

    //支付预售定金
    @Override
    @Transactional
    public PayData createPresellEarnest(String uid, String openid,String pid,
                                        String gid, String code,
                                        String type,String phone, String token,String comment,
                                        String emp) throws OrderExceptionApp {
        Info info = GetInfo(token);
        Presell presell = appPresellMapper.getDataById(pid);
        Goods goods = goodsMapper.getGoodsById(gid);
        Earnest earnest = new Earnest();
        earnest.setTpayed(presell.getDeposit());
        earnest.setDeductible(presell.getDeduction());
        earnest.setRem(String.valueOf(Integer.parseInt(presell.getPrice())-Integer.parseInt(earnest.getDeductible())));
        //实付金额 剩余金额+已付定金
        earnest.setPrice(String.valueOf(Integer.parseInt(earnest.getTpayed())+Integer.parseInt(earnest.getRem())));

        earnest.setPhone(phone);
        earnest.setGoodsType(type);
        earnest.setGid(gid);
        earnest.setCode(code);
        earnest.setComment(comment);
        earnest.setEmp(emp);
        earnest.setUid(uid);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdf.format(new Date());

        earnest.setToken(token);
        earnest.setCreateTime(now);
        earnest.setPid(pid);
        earnest.setErpId(emp);
        earnest.setState("N");

        earnest.setOrderId(getOrderIdByUUId());

        CreateYC_YSRETAIL createYC_ysretail = new CreateYC_YSRETAIL(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            String row = createYC_ysretail.getData(earnest);
            earnest.setErpId(row);
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }
        //生成订单待用
        String tot = String.valueOf(Integer.parseInt(earnest.getRem())+Integer.parseInt(earnest.getTpayed()));
        String oid = createOrder(uid, tot, phone, token, earnest.getOrderId(), goods, type, code, now);
        earnest.setOid(oid);
        //记录订单信息
        appPresellMapper.createEarnest(earnest);
        //生成预售定金单
        //生成支付
        PayData data = new PayData();
        try {
            String notify_url = "https://lfwd.cloudsmicro.com/shop/pay/earnest";
            data = payWechatService.createUnified(notify_url,openid, token, earnest.getOrderId(), earnest.getTpayed(), "定金");
            data.setOrderId(earnest.getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderExceptionApp(e.getMessage());
        }


        return data;
    }

    /**
     * 创建订单
     * @param uid
     * @param price
     * @param phone
     * @param token
     * @param orderid
     * @param goods
     * @param type
     * @param code
     * @return
     */
    private String createOrder(String uid,String price,String phone,String token,
                               String orderid,Goods goods,String type,String code,String now){


        Order order = new Order();
        order.setUid(uid);
   /*     order.setReceiver(address.getReceiver());
        order.setPhone(address.getPhone());
        order.setAddress(address.getAddress());*/

        order.setState("-1");
        order.setOrderTime(now);
        order.setTotalPrice(price);
        order.setTotalIntegral("0");
        order.setCreatedUser(phone);
        order.setCreatedTime(now);
        order.setModifiedUser(phone);
        order.setModifiedTime(now);
        order.setToken(token);
        order.setAccount(token);
        //封装订单号
        order.setOrderId(orderid+"-Y");
        order.setOrderType("YS");//类型预售

        // 执行插入订单数据
        insertOrder(order);

        OrderItem item = new OrderItem();
        // 向OrderItem对象中封装商品相关的5个数据
        item.setGoodsId(goods.getId());
        item.setGoodsTitle(goods.getName());
        item.setGoodsImage(goods.getImg());
        item.settName(type);
        item.setCode(code);
        item.setGoodsPrice(price);
        item.setGoodsIntegral(goods.getIntegral());
        item.setGoodsNum("1");
        // 向OrderItem对象中封装oid：order.getOid()
        item.setOid(order.getId());
        // 向OrderItem对象中封装日志
        item.setCreatedUser(phone);
        item.setCreatedTime(now);
        item.setModifiedUser(phone);
        item.setModifiedTime(now);
        // 执行插入订单商品数据
        insertOrderItem(item);

        return order.getId();
    }

    @Override
    public List<Presell> getData(String token) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        int ndate = Integer.parseInt(sdf.format(new Date()));

        List<Presell> presells = appPresellMapper.getData(token);
        List<Presell> data = new ArrayList<Presell>();
        for (Presell p : presells){
            if (ndate >= Integer.parseInt(p.getDepositTime())){
                p.setState(1);

            }
            if (ndate >= Integer.parseInt(p.getClearingTime())){
                p.setState(2);
            }
            if (ndate < Integer.parseInt(p.getClearingTime())){
                p.setGoods(goodsMapper.getGoodsById(p.getGid()));
                data.add(p);
            }


        }

        return data;

    }

    private Info GetInfo(String token) {
        return accountMapper.GetTokenData(token);
    }

    /**
     * 插入订单数据
     *
     * @param order 订单数据
     */
    private void insertOrder(Order order) throws OrderExceptionApp {
        Integer rows = orderMapper.insertOrder(order);
        if (rows != 1) {
            throw new OrderExceptionApp("创建订单数据时出现未知错误！");
        }
    }

    /**
     * 插入订单商品数据
     */
    private void insertOrderItem(OrderItem orderItem) throws OrderExceptionApp {
        Integer rows = orderMapper.insertOrderItem(orderItem);
        if (rows != 1) {
            throw new OrderExceptionApp("创建订单商品数据时出现未知错误！");
        }
    }
}
